package com.huajx.hanvon.handler;

import Com.FirstSolver.Splash.FaceId_Item;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huajx.core.kit.AsyncHttpClientKit;
import com.huajx.core.kit.HttpKit;
import com.huajx.core.message.RequestMessage;
import com.huajx.core.message.ResponseMessage;
import com.huajx.hanvon.Const;
import com.huajx.hanvon.HanvonTcpServer;
import com.huajx.util.CharsetUtil;
import com.huajx.util.StrUtil;
import com.huajx.util.io.FileUtil;

import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 * 处理命令下发
 */
public class GetRequestHandler extends AbstractHanvonHandler {
    private static final Logger logger = LoggerFactory.getLogger(GetRequestHandler.class);
    private String serverUrl;

    @Override
    public ResponseMessage handler(RequestMessage request) {

        String Answer = request.getMessage().toString();

        IoSession session = request.getSession();

        serverUrl = HanvonTcpServer.config.getServerUrl();

        // 获取设备序列号
        String SerialNumber = FaceId_Item.GetKeyValue(Answer, "sn");
        session.setAttribute(Const.KEY_SERIALNUMBER, SerialNumber);
        //session.write("GetEmployee(id=\"123456\")");
        //session.setAttribute("id","123456");4008109188 qq261608646
        /*try {
			String photo = read("C:\\Users\\Administrator\\Desktop\\command.txt");
			photo= new String(photo.getBytes("GBK"), "GBK");
			System.out.println(photo);
		    session.write(photo);
        } catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}*/
       /* String photo=read("C:\\Users\\Administrator\\Desktop\\command.txt");
        try {
			photo= new String(photo.getBytes("GBK"), "GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        session.write(photo);*/
        String content = null;
        try {
            Object res = HttpKit.get(serverUrl + Const.instruction + SerialNumber);
            if (res == null) {
                return null;
            }
            content = res.toString();
            if (StrUtil.isBlank(content)) {
                return null;
            }
        } catch (IOException e) {
            logger.error("请求{}出错，异常：{}", Const.instruction, e.getMessage());
            return null;
        }

        StringBuffer con = new StringBuffer();//修改的指令表记录
        StringBuffer commandSet = new StringBuffer("SetNameTable(");//需执行的指令
        StringBuffer commandAdd = new StringBuffer("AddNameTable(");
        StringBuffer commandDel = new StringBuffer("DeleteEmployee(");
        StringBuffer commandSetface = new StringBuffer("SetEmployee(");
        StringBuffer commandGet=new StringBuffer();
        JSONArray array = JSON.parseArray(content);
        Boolean flag=false;
        StringBuffer deleteAllids=new StringBuffer();
        for (int i = 0; i < array.size(); i++) {
        	JSONObject json = array.getJSONObject(i); 
        	String ids = json.getString("ids");//指令记录ID  
            String description = json.getString("description");   //需要执行的命令类型
            if("deleteAll".equals(description)){
            	flag=true;
            	//保存指令表需要修改状态的记录ID
                if (StrUtil.isNotBlank(ids)) {
                	deleteAllids.append(ids).append(",");
                }
            	continue;
            }
            String id = json.getString("id");//修改前的ID
            String modifId = json.getString("modifId");//修改后的id
            String address = json.getString("address");//修改的楼栋
            String names = json.getString("names");//人员名称
            String path = json.getString("path");//人员头像数据地址
            if ("update".equals(description)) {
                handleUpdate(commandSet, id, names);
            } else if ("add".equals(description)) {
                handleAdd(commandAdd, commandSetface, SerialNumber, address, modifId, id, names);
            } else if ("delete".equals(description)) {
                commandDel.append("id=\"").append(id).append("\" ");
            }else if("get".equals(description)){
            	String command="GetEmployee(id=\""+id+"\")";
            	session.write(command);
            } else if("set".equals(description)){
            	if(!StrUtil.isBlank(path)){
            		try {
            			String photo = read(path);
            			photo= new String(photo.getBytes("GBK"), "GBK");
            			System.out.println(photo);
            			session.write(photo);
            		} catch (Exception e) {
						// TODO: handle exception
            			e.printStackTrace();
					}
            	}
            }
            //保存指令表需要修改状态的记录ID
            if (StrUtil.isNotBlank(ids)) {
                con.append(ids);
            }
            if (i < array.size() - 1) {
                con.append(",");
            }
        }
        session.setAttribute("con", con.toString());
        //判断是否需要执行此指令

        commandSet.append(")");
        commandAdd.append(")");
        commandDel.append(")");
        commandSetface.append("\")");

        render(session, commandSet.toString());
        render(session, commandAdd.toString());
        render(session, commandDel.toString());
        render(session, commandSetface.toString());
        render(session, commandGet.toString(),1);
        if(flag){
        	render(session, "DeleteAllEmployee()",deleteAllids.toString());
        }

        return null;
    }

    /**
     * 执行命令
     * @param session
     * @param command
     */
    private void render(IoSession session, String command,String deleteAllids) {
    	session.setAttribute("con", deleteAllids);
    	session.write(command);
    }
    
    /**
     * 执行命令
     * @param session
     * @param command
     */
    private void render(IoSession session, String command) {
        if (StrUtil.contains(command, '=')) {
            session.write(command);
            logger.info(command);
        }
    }
    
    /**
     * 执行命令
     * @param session
     * @param command
     */
    private void render(IoSession session, String commands,int count) {
    	String[] commandSet = commands.split(";");
    	/*for (String command : commandSet) {
    		if(StrUtil.isBlank(command)){
    			continue;
    		}
    		WriteFuture write = session.write(command);
    		
		}*/
    }


    @Override
    public void render(IoSession session) {

    }

    private void handleUpdate(StringBuffer commandSet, String id, String names) {
        commandSet.append(id).append("=\"").append(names).append("\" ");
    }

    private void handleAdd(StringBuffer commandAdd, StringBuffer commandSetface, String serialNumber, String address, String modifId, String id, String names) {
        if (StrUtil.isNotBlank(address) && StrUtil.isNotBlank(id)) {
            modifId = id;
        }

        if (StrUtil.isBlank(modifId)) {
        	System.out.println(names);
        	try {
        		names= new String(names.getBytes("GBK"), "GBK");
			} catch (Exception e) {
			
			}
        	
            commandAdd.append(id).append("=\"").append(names).append("\" ");
            return;
        }

        String getFaceUrl = StrUtil.format(Const.get_face, serialNumber, id);

        JSONArray facesArray = null;

        try {
            Object faces = HttpKit.get(serverUrl + getFaceUrl);
            if (faces == null) {
                return;
            }
            facesArray = JSON.parseArray(faces.toString());
        } catch (Throwable e) {
            logger.error("请求{}出错，异常：{}", getFaceUrl, e.getMessage());
            return;
        }

        if (facesArray == null || facesArray.isEmpty()) {
            return;
        }

        for (int i = 0; i < facesArray.size(); i++) {
            JSONObject fjson = facesArray.getJSONObject(i);
            String cardNum = fjson.getString("cardNum");
            String authority = fjson.getString("authority");
            String checkType = fjson.getString("checkType");
            String calid = fjson.getString("calid");
            String face_data = fjson.getString("face_data");

            if (StrUtil.isBlank(face_data)) {
                continue;
            }

            Object data = null;

            try {
                data = HttpKit.get(face_data);
            } catch (IOException e) {
                logger.error("请求图片出错{}", face_data);
                continue;
            }

            if (data == null) {
                continue;
            }

            commandSetface.append("id=\"").append(modifId).append("\" ").append("name=\"").append(names).append("\" ").append("calid=\"").append(calid).append("\" ").append("card_num=\"").append(cardNum).append("\" ").append("authority=\"").append(authority).append("\" ").append("check_type=\"").append(checkType).append("\" ").append("opendoor_type=\"face&card\" ").append(data.toString());

            logger.info(face_data);
        }

        AsyncHttpClientKit.get(serverUrl + "/a/face/updateFace?id=" + id + "&modifId=" + modifId, content -> {
        });

    }
    
    public static String read1(String filePath) throws IOException{
    	File file = new File(filePath);
    	String string = FileUtil.readString(file, CharsetUtil.GBK);
    	return string;
    }
    
    public static void main(String[] args) throws IOException {
    	String photo=read("C:\\Users\\Administrator\\Desktop\\command.txt");
    	System.out.println(photo);
	}
    
    private static String read(String filePath) {
        int HttpResult; // 服务器返回的状态
        String ee = new String();
        try
        {
            URL url =new URL(filePath); // 创建URL
            URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
            urlconn.connect();
            HttpURLConnection httpconn =(HttpURLConnection)urlconn;
            HttpResult = httpconn.getResponseCode();
            if(HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.print("无法连接到");
            } else {
                InputStreamReader isReader = new InputStreamReader(urlconn.getInputStream(),"UTF-8");
                BufferedReader reader = new BufferedReader(isReader);
                StringBuffer buffer = new StringBuffer();
                String line; // 用来保存每行读取的内容
                line = reader.readLine(); // 读取第一行
                while (line != null) { // 如果 line 为空说明读完了
                    buffer.append(line); // 将读到的内容添加到 buffer 中
                    line = reader.readLine(); // 读取下一行
                }
                ee = buffer.toString();
            }
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return  ee;
    }

}
